/*
 * @Author: xiaosihan 
 * @Date: 2024-08-14 20:27:50 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-09-01 17:46:15
 */

import tinypngApi from "@api/tinypngApi";
import { TinypngkeyData } from "@type";
import { get, isEmpty } from "lodash";
import { observable, configure } from "mobx";
configure({ enforceActions: "never" });

const homeStore = observable({
    page: 1,//当前页面
    pageSize: 10,//分页数
    total: 0,//总数
    list: [] as Array<TinypngkeyData>,//数据列表
    sumResidue: 0, // 剩余数量
    sumCompressionCount: 0, // 已用数量
    //请求数据
    async getList(page: number = 1, pageSize: number = 10) {
        this.page = page;
        this.pageSize = pageSize;

        const result = await tinypngApi.get_key_list(page, pageSize);
        const list = get(result, ["list"]) || [];
        const total = get(result, ["total"]) || 0;
        const sumResidue = get(result, ["sumResidue"]) || 0;
        const sumCompressionCount = get(result, ["sumCompressionCount"]) || 0;

        this.list = list;
        this.total = total;
        this.sumResidue = sumResidue;
        this.sumCompressionCount = sumCompressionCount;
    },
    //新增数据
    async add(key: string) {
        const addResult = await tinypngApi.add_key(key, this.page, this.pageSize).catch(() => { });

        const list = get(addResult, ["list"]) || [];
        const total = get(addResult, ["total"]) || 0;
        const sumResidue = get(addResult, ["sumResidue"]) || 0;
        const sumCompressionCount = get(addResult, ["sumCompressionCount"]) || 0;

        if (!isEmpty(list)) {
            this.list = list;
            this.total = total;
            this.sumResidue = sumResidue;
            this.sumCompressionCount = sumCompressionCount;
        }
    },
    //校验所有的key
    async validate_all_key() {
        await tinypngApi.validate_all_key();
        this.getList();
    },
    //删除数据
    delete(id: string) {
        // 删除完后请求数据
        this.getList();
    },
    //更新数据
    async updateResidue(key: string, compressionCount: number, residue: number) {
        try {
            const result = await tinypngApi.update_residue(key, compressionCount, residue);
            if (result) {
                this.getList();
                return true;
            }
            return false;
        } catch (error) {
            console.error('更新余额和已用数量失败:', error);
            return false;
        }
    }

}, {}, { deep: false });
homeStore.getList();
export default homeStore;